Completed
Push — master ( cdadad...8d09a6 )
by Dimas
36:02 queued 17:12
created

process.doProcess   B

Complexity

Conditions 5

Size

Total Lines 34
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 23
dl 0
loc 34
rs 8.8613
c 0
b 0
f 0
1
import filemanager from "./filemanager";
2
import fs from "fs";
3
import upath from "upath";
4
import log from "./log";
5
import { MD5 } from "crypto-js";
6
import coreProcess from "process";
7
8
const savetemp = "./tmp/compiler";
9
if (fs.existsSync(savetemp)) {
10
  filemanager.empty(upath.join(coreProcess.cwd(), savetemp), null);
11
}
12
13
class process {
14
  static root = coreProcess.cwd();
15
  static verbose: boolean = false;
16
  static tmp = savetemp;
17
  /**
18
   * Create lock file
19
   * @param file
20
   */
21
  static lockCreate(file: string) {
22
    return upath.join(coreProcess.cwd(), this.tmp, MD5(file).toString());
23
  }
24
  /**
25
   * lock the process
26
   * @param lockfile
27
   */
28
  private static lockProcess(lockfile: string) {
29
    if (this.verbose) {
30
      log.log(log.random("locking process"));
31
    }
32
    if (!upath.resolve(upath.dirname(lockfile))) {
33
      filemanager.mkdir(upath.dirname(lockfile));
34
    }
35
    filemanager.mkfile(lockfile, "lockfile");
36
  }
37
  /**
38
   * release lock process
39
   * @param lockfile
40
   */
41
  private static releaseLock(lockfile: string) {
42
    if (this.verbose) {
43
      log.log(log.random("releasing process"));
44
    }
45
    if (fs.existsSync(lockfile)) {
46
      filemanager.unlink(lockfile, false);
47
    } else {
48
      if (this.verbose) {
49
        log.log(log.error("process file already deleted"));
50
      }
51
    }
52
  }
53
  /**
54
   * do process
55
   * @param lockfile
56
   * @param callback
57
   */
58
  static doProcess(
59
    lockfile: string,
60
    options: { verbose: boolean } | any,
61
    callback: Function
62
  ) {
63
    if (typeof options.verbose == "boolean") {
64
      this.verbose = options.verbose;
65
    }
66
    lockfile = process.lockCreate(lockfile);
67
    if (fs.existsSync(lockfile)) {
68
      log.log(
69
        log.error(`Process locked (${lockfile}). please provide unique ids.`)
70
      );
71
      return null;
72
    }
73
    const doCall = function () {
74
      if (typeof callback == "function") {
75
        return callback(lockfile);
76
      } else if (typeof options == "function") {
77
        return options(lockfile);
78
      }
79
    };
80
    process.lockProcess(lockfile);
81
    const load = new Promise((resolve, reject) => {
82
      doCall();
83
      resolve(true);
84
    });
85
    load.then(function () {
86
      process.releaseLock(lockfile);
87
    });
88
  }
89
}
90
91
export = process;
92